#pragma once

#include <iostream>
#include <string>
#include <functional>
#include <unistd.h>

namespace My_Thread
{
    using func_t = std::function<void()>;
    static int num = 1; // 线程个数计数

    enum class TSTATUS
    {
        NEW,
        RUNNING,
        STOP
    };

    class Thread
    {
    private:
        static void *routine(void *args)
        {
            Thread *t = static_cast<Thread *>(args);
            t->_status = TSTATUS::RUNNING;
            t->_func();
            return nullptr;
        }

    public:
        Thread(func_t func) : _func(func)
        {
            _name = "thread-" + std::to_string(num); // 默认命名
            _status = TSTATUS::NEW;
            _joinable = true;
            _pid = getpid();
        }

        bool Start()
        {
            if (_status == TSTATUS::RUNNING)
                return true;

            int n = ::pthread_create(&_tid, nullptr, routine, this);
            if (n != 0)
                return false;

            return true;
        }
        bool Jion()
        {
            if (_joinable)
            {
                int n = ::pthread_join(_tid, nullptr);
                if (n != 0)
                    return false;
                _status = TSTATUS::STOP;
                return true;
            }
            return false;
        }
        bool Stop()
        {
            if (_status == TSTATUS::RUNNING)
            {
                int n = ::pthread_cancel(_tid);
                if (n != 0)
                    return false;
                _status = TSTATUS::STOP;
                return true;
            }
            return false;
        }
        bool Detach()
        {
            _joinable = false;
            int n = ::pthread_detach(_tid);
            if (n != 0)
                return false;
            return true;
        }

        bool IsJoinable()
        {
            return _joinable;
        }

        std::string Name()
        {
            return _name;
        }

        ~Thread()
        {
        }

    private:
        std::string _name;
        pthread_t _tid;
        pid_t _pid;
        bool _joinable;
        func_t _func;
        TSTATUS _status;
    };
}
